<template>
  <div class="dashboard" v-loading="loading">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon user-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ totalUsers }}</div>
              <div class="stats-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon role-icon">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ totalRoles }}</div>
              <div class="stats-label">总角色数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon permission-icon">
              <el-icon><Lock /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ totalPermissions }}</div>
              <div class="stats-label">总权限数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon log-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ totalLogs }}</div>
              <div class="stats-label">操作日志</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户登录趋势 (最近30天)</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="loginTrendOption" style="height: 300px; width: 100%;" />
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户活跃度趋势 (最近30天)</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="userActivityOption" style="height: 300px; width: 100%;" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>操作类型分布</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="operationTypeOption" style="height: 300px; width: 100%;" />
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>今日小时活跃度</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="hourlyActivityOption" style="height: 300px; width: 100%;" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 统计摘要卡片 -->
    <el-row :gutter="20" class="summary-row">
      <el-col :span="12">
        <el-card class="summary-card">
          <template #header>
            <div class="card-header">
              <span>登录统计摘要</span>
            </div>
          </template>
          <div class="summary-content">
            <div class="summary-item">
              <div class="summary-label">今日登录</div>
              <div class="summary-value">{{ todayLoginCount }}</div>
            </div>
            <div class="summary-item">
              <div class="summary-label">本月登录</div>
              <div class="summary-value">{{ monthLoginCount }}</div>
            </div>
            <div class="summary-item">
              <div class="summary-label">平均每日登录</div>
              <div class="summary-value">{{ avgDailyLogin }}</div>
            </div>
            <div class="summary-item">
              <div class="summary-label">最高单日登录</div>
              <div class="summary-value">{{ maxDailyLogin }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="summary-card">
          <template #header>
            <div class="card-header">
              <span>活跃度统计摘要</span>
            </div>
          </template>
          <div class="summary-content">
            <div class="summary-item">
              <div class="summary-label">今日活跃</div>
              <div class="summary-value">{{ todayActivityCount }}</div>
            </div>
            <div class="summary-item">
              <div class="summary-label">本月活跃</div>
              <div class="summary-value">{{ monthActivityCount }}</div>
            </div>
            <div class="summary-item">
              <div class="summary-label">平均每日活跃</div>
              <div class="summary-value">{{ avgDailyActivity }}</div>
            </div>
            <div class="summary-item">
              <div class="summary-label">最高单日活跃</div>
              <div class="summary-value">{{ maxDailyActivity }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细信息表格 -->
    <el-card class="detail-section">
      <template #header>
        <div class="card-header">
          <span>系统详细信息</span>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <h4>用户统计</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="活跃用户">{{ activeUsers }}</el-descriptions-item>
            <el-descriptions-item label="禁用用户">{{ inactiveUsers }}</el-descriptions-item>
            <el-descriptions-item label="封禁用户">{{ bannedUsers }}</el-descriptions-item>
            <el-descriptions-item label="今日新增">{{ stats.todayNewUsers || 0 }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="8">
          <h4>角色统计</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="激活角色">{{ activeRoles }}</el-descriptions-item>
            <el-descriptions-item label="禁用角色">{{ inactiveRoles }}</el-descriptions-item>
            <el-descriptions-item label="平均权限数">{{ stats.avgPermissionsPerRole || 0 }}</el-descriptions-item>
            <el-descriptions-item label="今日新增">{{ stats.todayNewRoles || 0 }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="8">
          <h4>系统信息</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="系统版本">{{ systemInfo.version || '1.0.0' }}</el-descriptions-item>
            <el-descriptions-item label="运行时间">{{ systemInfo.uptime || '0天' }}</el-descriptions-item>
            <el-descriptions-item label="数据库连接">{{ systemInfo.dbStatus || '正常' }}</el-descriptions-item>
            <el-descriptions-item label="最后更新">{{ formatDate(systemInfo.lastUpdate) }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
    </el-card>

    <!-- 最活跃用户列表 -->
    <el-card class="detail-section">
      <template #header>
        <div class="card-header">
          <span>最活跃用户</span>
        </div>
      </template>
      
      <el-table :data="stats.topUsers" stripe style="width: 100%">
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="realName" label="姓名" width="150" />
        <el-table-column prop="operationCount" label="操作次数" width="120" />
      </el-table>
    </el-card>

    <!-- 最新操作日志 -->
    <el-row :gutter="20" class="logs-row">
      <el-col :span="24">
        <el-card class="logs-card">
          <template #header>
            <div class="card-header">
              <span>最新操作日志</span>
              <el-button type="primary" size="small" @click="$router.push('/logs')">
                查看更多
              </el-button>
            </div>
          </template>
          
                     <el-table :data="recentLogs" style="width: 100%" v-loading="loading">
             <el-table-column prop="action" label="操作" width="150" />
             <el-table-column prop="user.username" label="用户" width="120" />
             <el-table-column prop="ipAddress" label="IP地址" width="120" />
             <el-table-column label="详情" show-overflow-tooltip>
               <template #default="{ row }">
                 <div class="details-cell">
                   <div v-if="row.resource" class="resource-info">
                     <el-tag type="info" size="small">{{ row.resource }}</el-tag>
                     <span v-if="row.resourceId" class="resource-id">ID: {{ row.resourceId }}</span>
                   </div>
                   <div v-if="row.details" class="details-content">
                     {{ formatDetails(row.details) }}
                   </div>
                 </div>
               </template>
             </el-table-column>
             <el-table-column prop="createdAt" label="时间" width="180">
               <template #default="{ row }">
                 {{ formatDate(row.createdAt) }}
               </template>
             </el-table-column>
           </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import dayjs from 'dayjs'
import { systemApi, logApi } from '@/api'
import type { SystemStats, OperationLog } from '@/types'
import { User, UserFilled, Lock, Document } from '@element-plus/icons-vue'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const loading = ref(false)
const stats = ref<SystemStats>({
  users: { total: 0, active: 0, banned: 0 },
  roles: { total: 0, active: 0 },
  permissions: { total: 0 },
  configs: { total: 0 },
  logs: { total: 0, today: 0, last7Days: [] },
  topUsers: [],
  topActions: []
})
const recentLogs = ref<OperationLog[]>([])
const systemInfo = ref({
  version: '1.0.0',
  uptime: '0天',
  dbStatus: '正常',
  lastUpdate: new Date()
})

// 计算属性 - 兼容性字段
const totalUsers = computed(() => stats.value.users?.total || stats.value.totalUsers || 0)
const totalRoles = computed(() => stats.value.roles?.total || stats.value.totalRoles || 0)
const totalPermissions = computed(() => stats.value.permissions?.total || stats.value.totalPermissions || 0)
const totalLogs = computed(() => stats.value.logs?.total || stats.value.totalLogs || 0)
const activeUsers = computed(() => stats.value.users?.active || stats.value.activeUsers || 0)
const inactiveUsers = computed(() => stats.value.inactiveUsers || 0)
const bannedUsers = computed(() => stats.value.users?.banned || stats.value.bannedUsers || 0)
const activeRoles = computed(() => stats.value.roles?.active || stats.value.activeRoles || 0)
const inactiveRoles = computed(() => stats.value.inactiveRoles || 0)

// 登录统计计算属性
const todayLoginCount = computed(() => {
  const today = new Date().toISOString().split('T')[0]
  const loginTrend = stats.value.loginTrend?.daily || []
  return loginTrend.find(item => item.date === today)?.count || 0
})

const monthLoginCount = computed(() => {
  const currentMonth = new Date().toISOString().slice(0, 7)
  const monthlyLoginTrend = stats.value.loginTrend?.monthly || []
  return monthlyLoginTrend.find(item => item.month === currentMonth)?.count || 0
})

const avgDailyLogin = computed(() => {
  const loginTrend = stats.value.loginTrend?.daily || []
  if (loginTrend.length === 0) return 0
  const total = loginTrend.reduce((sum, item) => sum + item.count, 0)
  return (total / loginTrend.length).toFixed(1)
})

const maxDailyLogin = computed(() => {
  const loginTrend = stats.value.loginTrend?.daily || []
  if (loginTrend.length === 0) return 0
  return Math.max(...loginTrend.map(item => item.count))
})

// 活跃度统计计算属性
const todayActivityCount = computed(() => {
  const today = new Date().toISOString().split('T')[0]
  const userActivity = stats.value.userActivity?.daily || []
  return userActivity.find(item => item.date === today)?.count || 0
})

const monthActivityCount = computed(() => {
  const currentMonth = new Date().toISOString().slice(0, 7)
  const monthlyUserActivity = stats.value.userActivity?.monthly || []
  return monthlyUserActivity.find(item => item.month === currentMonth)?.count || 0
})

const avgDailyActivity = computed(() => {
  const userActivity = stats.value.userActivity?.daily || []
  if (userActivity.length === 0) return 0
  const total = userActivity.reduce((sum, item) => sum + item.count, 0)
  return (total / userActivity.length).toFixed(1)
})

const maxDailyActivity = computed(() => {
  const userActivity = stats.value.userActivity?.daily || []
  if (userActivity.length === 0) return 0
  return Math.max(...userActivity.map(item => item.count))
})

// 用户登录趋势图表配置
const loginTrendOption = computed(() => {
  const loginTrend = stats.value.loginTrend?.daily || []
  const dates = loginTrend.map(item => item.date)
  const counts = loginTrend.map(item => item.count)
  
  return {
    title: {
      text: '用户登录趋势 (最近30天)',
      left: 'center',
      top: 10
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: {c} 次登录'
    },
    grid: {
      top: 60,
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates.length > 0 ? dates : ['暂无数据'],
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '登录次数'
    },
    series: [
      {
        name: '登录次数',
        type: 'line',
        data: counts.length > 0 ? counts : [0],
        smooth: true,
        itemStyle: {
          color: '#67c23a'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
              { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
            ]
          }
        }
      }
    ]
  }
})

// 用户活跃度趋势图表配置
const userActivityOption = computed(() => {
  const userActivity = stats.value.userActivity?.daily || []
  const dates = userActivity.map(item => item.date)
  const counts = userActivity.map(item => item.count)
  
  return {
    title: {
      text: '用户活跃度趋势 (最近30天)',
      left: 'center',
      top: 10
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: {c} 个活跃用户'
    },
    grid: {
      top: 60,
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates.length > 0 ? dates : ['暂无数据'],
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '活跃用户数'
    },
    series: [
      {
        name: '活跃用户数',
        type: 'line',
        data: counts.length > 0 ? counts : [0],
        smooth: true,
        itemStyle: {
          color: '#409eff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      }
    ]
  }
})

// 操作类型分布图表配置
const operationTypeOption = computed(() => {
  const topActions = stats.value.topActions || []
  const data = topActions.map(action => ({
    value: action.count,
    name: action.action
  }))
  
  return {
    title: {
      text: '操作类型分布',
      left: 'center',
      top: 10
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 40
    },
    series: [
      {
        name: '操作类型',
        type: 'pie',
        radius: '50%',
        center: ['60%', '60%'],
        data: data.length > 0 ? data : [
          { value: 0, name: '暂无数据' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
})

// 系统资源使用情况图表配置
const resourceUsageOption = computed(() => ({
  title: {
    text: '系统资源使用情况',
    left: 'center',
    top: 10
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    data: ['CPU', '内存', '磁盘'],
    top: 40
  },
  grid: {
    top: 80,
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00']
  },
  yAxis: {
    type: 'value',
    max: 100
  },
  series: [
    {
      name: 'CPU',
      type: 'bar',
      data: [20, 15, 30, 45, 60, 40, 25],
      itemStyle: { color: '#67c23a' }
    },
    {
      name: '内存',
      type: 'bar',
      data: [30, 25, 40, 55, 70, 50, 35],
      itemStyle: { color: '#e6a23c' }
    },
    {
      name: '磁盘',
      type: 'bar',
      data: [50, 45, 60, 75, 80, 70, 55],
      itemStyle: { color: '#f56c6c' }
    }
  ]
}))

// 今日小时活跃度图表配置
const hourlyActivityOption = computed(() => {
  const hourlyData = stats.value.loginTrend?.hourly || stats.value.userActivity?.hourly || []
  const hours = hourlyData.map(item => `${item.hour}:00`)
  const counts = hourlyData.map(item => item.count)
  
  return {
    title: {
      text: '今日小时活跃度',
      left: 'center',
      top: 10
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: {c} 个活跃用户'
    },
    grid: {
      top: 60,
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: hours.length > 0 ? hours : ['暂无数据'],
      axisLabel: {
        interval: 2
      }
    },
    yAxis: {
      type: 'value',
      name: '活跃用户数'
    },
    series: [
      {
        name: '活跃用户数',
        type: 'bar',
        data: counts.length > 0 ? counts : [0],
        itemStyle: {
          color: '#e6a23c',
          borderRadius: [4, 4, 0, 0]
        }
      }
    ]
  }
})

// 格式化日期
const formatDate = (date: string | Date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 格式化详情内容
const formatDetails = (details: any) => {
  if (!details) return '-'
  
  if (typeof details === 'string') {
    return details
  }
  
  if (typeof details === 'object') {
    try {
      return JSON.stringify(details, null, 2)
    } catch {
      return String(details)
    }
  }
  
  return String(details)
}

// 获取统计数据
const fetchStats = async () => {
  loading.value = true
  try {
    const response = await systemApi.stats()
    stats.value = response.data
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取系统统计信息失败')
  } finally {
    loading.value = false
  }
}

// 获取最新日志
const fetchRecentLogs = async () => {
  try {
          const response = await logApi.getList({ page: 1, limit: 10 })
    recentLogs.value = response.data.data || []
  } catch (error) {
    console.error('获取最新日志失败:', error)
  }
}

onMounted(() => {
  fetchStats()
  fetchRecentLogs()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  height: 120px;
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.user-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.role-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.permission-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.log-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.summary-row {
  margin-bottom: 20px;
}

.summary-card {
  height: 280px;
}

.summary-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  height: 100%;
  align-items: center;
}

.summary-item {
  text-align: center;
  padding:10px 6px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.summary-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.summary-label {
  font-size: 12px;
  color: #6c757d;
  margin-bottom: 8px;
  font-weight: 500;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #495057;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  width: 100%;
}

.detail-section {
  margin-bottom: 20px;
}

.logs-card {
  height: 500px;
}

h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.details-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.resource-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.resource-id {
  font-size: 12px;
  color: #909399;
  background-color: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
}

.details-content {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
  max-height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  word-break: break-all;
}
</style> 